package com.cmcc.passenger.ui.onorder


import android.app.Activity
import android.content.SharedPreferences
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.cmcc.passenger.AppManager
import com.cmcc.passenger.R
import com.cmcc.passenger.config.PassPath
import com.cmcc.passenger.data.entity.response.Gratuity
import com.cmcc.passenger.data.entity.response.OrderTemplate
import com.cmcc.passenger.databinding.ActivityOnOrderBinding
import com.cmcc.passenger.ui.base.BasicActivity
import com.cmcc.passenger.ui.fragment.AppAlertDialog
import com.cmcc.passenger.ui.fragment.AppProgressDialog
import com.cmcc.passenger.ui.fragment.CancelReasonDialogFragment
import com.cmcc.passenger.ui.onorder.adapter.OnOrderTipAdapter
import com.cmcc.passenger.ui.onorder.adapter.OnOrderTipItemClickListener
import com.cmcc.passenger.ui.utils.NumberUtils
import com.cmcc.shared.adapter.TripOptionItemDecoration
import com.cmcc.shared.data.MessageEvent
import com.cmcc.shared.data.PassenMainEvent
import com.cmcc.shared.utils.DisplayUtil
import com.cmcc.shared.utils.clickWithTrigger
import java.text.SimpleDateFormat
import java.util.*

@Route(path = PassPath.ON_ORDER)
class OnOrderActivity : BasicActivity() {


    private lateinit var binding: ActivityOnOrderBinding
    private var orderRequest: OrderTemplate? = null
    private lateinit var viewModel: OnOrderViewModel

    private var tipAdapter: OnOrderTipAdapter? = null

    private var orderTempId: String? = null

    private var progressDialog: AppProgressDialog? = null

    private var timer: Timer? = null
    private var waitMessage = MutableLiveData<String>()
    private var tempBountyFee: Double = 0.0

    private val mode by lazy {
        getSharedPreferences("SP_Passenger", Activity.MODE_PRIVATE).getInt("mode", 1)
    }

    override fun initialize(savedInstanceState: Bundle?) {
        AppManager.add(this);
        viewModel = ViewModelProviders.of(this).get(OnOrderViewModel::class.java)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_on_order)
        binding.toolbar.title.text = getString(R.string.on_order_title)
        binding.toolbar.toolbar.setNavigationOnClickListener { finish() }
        binding.viewModel = viewModel
        viewModel.cancelSelector().observe(this, Observer {
            val fragment = CancelReasonDialogFragment.newFragment()
            fragment.setOnCommitClickListener(object :
                CancelReasonDialogFragment.OnCommitClickListener {
                override fun onCommitClick(remark: String) {
                    progressDialog?.show()
                    cancelOrder(remark)
                }

            })
            fragment.show(supportFragmentManager, "CancelReasonDialogFragment")
        })
//        orderRequest = intent.getParcelableExtra(IntentKeys.ORDER_REQUEST)
        orderTempId = intent.getStringExtra("order_temp_id")


        binding.onOrderCurrentStatus.nearby.clickWithTrigger {
            when(mode) {
                1 -> {
                    val x = orderRequest?.startCoordinates?.x ?: 0.0
                    val y = orderRequest?.startCoordinates?.y ?: 0.0
                    if (x == 0.0 && y == 0.0)
                        Toast.makeText(
                            this,
                            getString(R.string.passenger_no_car_find_nearby),
                            Toast.LENGTH_LONG
                        ).show()
                    else
                        ARouter.getInstance().build(PassPath.CAR_NEARBY)
                            .withDouble("x", x)
                            .withDouble("y", y)
                            .withString("startAddress", orderRequest?.startAddress)
                            .withString("endAddress", orderRequest?.endAddress)
//                    .withString("createTime", orderRequest?.createTime)
                            .navigation()
                }
                2 -> {
                    //不跳转
                }
            }
        }

//        //通知首页 刷新接单的按钮
//
//        var  event = MessageEvent()
//        var  passenMainEvent = PassenMainEvent()
//        passenMainEvent.code = 200
//        event.passenMainEvent = passenMainEvent
//        org.greenrobot.eventbus.EventBus.getDefault().post(event);

    }

    fun cancelOrder(remark: String) {
        viewModel.cancelCall(orderTempId ?: "", remark)
    }


    private fun bindViewData() {

        binding.onOrderDirection.directionStart.text =
            getString(R.string.passenger_origin) + orderRequest?.startAddress
        binding.onOrderDirection.directionEnd.text =
            getString(R.string.passenger_destination) + orderRequest?.endAddress

        binding.onOrderRemarks.orderRemarks1.text =
            getCatTypeName(orderRequest?.vehicleTypeName)

        binding.onOrderRemarks.orderRemarks2.text =
                    getTunnelName(orderRequest?.tunnelName)

        binding.onOrderRemarks.orderRemarks3.text =
                    getStationName(orderRequest?.stationIndex?.toInt())
        binding.onOrderRemarks.remarkCount.text = getRemark(orderRequest?.remark)

        if (!orderRequest?.bountyFee.equals("0")) {
            var feeDouble = orderRequest?.bountyFee?.toDouble();
            binding.onOrderTip.amountOfTip.setText(   NumberUtils.forNormalMatNumber(feeDouble!!))
        }

        binding.onOrderCurrentStatus.orderNumber.text =
            getString(R.string.order_number, orderRequest?.orderNumber)


        binding.onOrderCurrentStatus.nearby.text = getString(R.string.nearby_car_count, 0)

        if (orderRequest?.type?.equals(2)!!) {
            binding.onOrderDirection.orderType.text =
                resources.getString(R.string.order_reservation)
            binding.onOrderDirection.orderDate.text =
                resources.getString(R.string.order_time_title) + " " + orderRequest!!.startTime
        } else {
            binding.onOrderDirection.orderType.text = resources.getString(R.string.order_real_time)
            binding.onOrderDirection.orderDate.text = resources.getString(R.string.trip_time)
        }



        viewModel.getNearbyDriver(
            orderRequest?.startCoordinates?.y,
            orderRequest?.startCoordinates?.x
        )


    }

    override fun onResume() {
        super.onResume()
        startTimer()
    }

    private fun startTimer() {
        timer = Timer()
        val task = object : TimerTask() {
            override fun run() {
                if (null != orderRequest) {
                    val createDate: Date =
                        SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(orderRequest?.createTime)
                    val timeGap = (Date().time - createDate.time) / 1000

                    runOnUiThread {
                        waitMessage.value =
                            getString(R.string.passenger_on_order_time_has_waiting, timeGap)
                    }
                }
            }
        }
        timer?.schedule(task, 0, 1000L)
    }

    override fun onPause() {
        timer?.cancel()
        timer = null
        super.onPause()
    }

    override fun initView(savedInstanceState: Bundle?) {
        progressDialog = AppProgressDialog(this)
        val divider =
            TripOptionItemDecoration(
                DisplayUtil.dp2px(this, 16f).toInt(),
                DisplayUtil.dp2px(this, 16f).toInt()
            )
        binding.onOrderTip.tipRecyclerView.addItemDecoration(divider)
        tipAdapter = OnOrderTipAdapter()
        binding.onOrderTip.tipRecyclerView.adapter = tipAdapter

    }

    override fun initEvent(savedInstanceState: Bundle?) {
        progressDialog?.show()
        viewModel.getOrderTemplate(orderTempId ?: "")
        tipAdapter?.setOnItemClickListener(object : OnOrderTipItemClickListener {
            override fun onClick(model: Gratuity, position: Int) {
                if (model.fee != 0.0) {
                    var feeDouble = model.fee

                    AppAlertDialog(this@OnOrderActivity).setContent(
                        getString(
                            R.string.plz_make_sure_fee,
                            NumberUtils.forNormalMatNumber(feeDouble!!)
                        )
                    )
                        .setNavigation(getString(R.string.cancel), null)
                        .setPositive(getString(R.string.make_ok),
                            View.OnClickListener {
                                viewModel.updateBounty(orderTempId ?: "", model.fee.toString())
                                tempBountyFee = model.fee
//                                if (tipAdapter?.checkedPosition != position) {
//                                    checkTipItem(position)
//                                }
                            }).show()
                }
            }

        })
    }

    private fun getCatTypeName(name: String?): String {
        return getString(R.string.passenger_car_type_with_colon)+" " + if (name == null) getString(R.string.passenger_any_with_space) else "$name "
    }

    private fun getTunnelName(name: String?): String {
        return getString(R.string.passenger_tunnel_with_colon) + if (name == null) getString(R.string.passenger_any_with_space) else "$name "
    }

    private fun getStationName(name: Int?): String {
        return getString(R.string.passenger_station_with_colon) + if (name == null || name == 0) getString(
            R.string.passenger_any_with_space
        ) else "$name "
    }

    private fun getRemark(name: String?): String {
        return getString(R.string.passenger_remark_with_colon) +"  "+ if (name.isNullOrBlank() || name.isNullOrEmpty()) getString(
            R.string.none_with_space
        ) else "$name"
    }

    private fun checkTipItem(index: Int) {
        binding.onOrderTip.tipRecyclerView.findViewHolderForAdapterPosition(
            index
        )?.itemView?.isSelected = true
        tipAdapter?.checkedPosition = index
        tipAdapter?.notifyDataSetChanged()
    }

    override fun initObserver(savedInstanceState: Bundle?) {

        viewModel.orderTemplate.observe(this, Observer {
            progressDialog?.dismiss()
            if (null != it) {
                //默认先加个0元的消费 因为 不加的时候 会有BUG 第一次加小费会翻倍 后台的问题。，
                viewModel.updateBounty(orderTempId ?: "", "0")
                orderRequest = it
                bindViewData()

                viewModel.getTipList().observe(this, Observer { gratuity ->
                    var tips = gratuity
                    tips -= gratuity[0]

                    tipAdapter?.submitList(tips)
//                    Handler().postDelayed({
//
//                        gratuity.forEachIndexed { index, tip ->
//                            if (tip.fee.toString() == orderRequest?.bountyFee) {
//                                checkTipItem(index - 1)
//                            }
//                        }
//                    }, 500)
                })

                viewModel.nearbyCar.observe(this, Observer { cars ->
                    when(mode) {
                        1 -> {
                            binding.onOrderCurrentStatus.nearby.text =
                                getString(R.string.nearby_car_count, cars.size)
                        }
                        2 -> {
                            binding.onOrderCurrentStatus.nearby.text =
                                getString(R.string.nearby_car_count, (3..9).random())
                        }
                    }
                })
            } else {
                finish()
            }

        })

        waitMessage.observe(this, Observer {
            binding.onOrderCurrentStatus.message.text = it
        })
        viewModel.cancelCall.observe(this, Observer { code ->
            progressDialog?.dismiss()
//            if (code == 200) {
//                finish()
//            } else
            if (code == 1001) {
                viewModel.queryOrderProgress()
            } else {
                finish()
            }

        })

        viewModel.processOrder.observe(this, Observer { order ->
            if (order?.id != null && order?.status != 0) {
                when(order.handleMode) {
                    1 ->
                        ARouter.getInstance().build(PassPath.ORDER_DETAIL)
                            .withString("order_id", order.id)
                            .withBoolean("is_doing", false)
                            .navigation()
                    2 ->
                        ARouter.getInstance().build(PassPath.CALL_ORDER_DETAIL)
                            .withString("order_id", order.id)
                            .navigation()
                }
            }
            finish()
        })

        viewModel.updatedSuccess.observe(this, Observer { success ->
            if (success) {
                viewModel.getOrderTemplate(orderTempId ?: "")
//                    val tipStr = binding.onOrderTip.amountOfTip.text.toString()
//                    val oldFee: Double = if (tipStr.isNotEmpty()) tipStr.toDouble() else 0.0
//
//                    binding.onOrderTip.amountOfTip.setText((oldFee + tempBountyFee).toString())

                //                viewModel.getTipList().observe(this, Observer { gratuity ->
                //                    gratuity.forEachIndexed { index, tip ->
                //                        if (tipAdapter?.checkedPosition == index - 1) {
                //                            binding.onOrderTip.amountOfTip.setText((oldFee + tip.fee).toString())
                //                        }
                //                    }
                //                })
            }
        })
    }


}